<template>
  <div v-loading="loading" class="purchase">
    <searchHead :search-data="searchData" :goods-library="true" @search="handleCurrentChange(1)" @reset="reset" @download="downloadExc" />
    <essTable
      ref="table"
      :thead-list="theadList"
      :resize-observer-ele="resizeObserverEle"
      :other-container-box="otherContainerBox"
      :page-num="searchData.pageNum - 1 + 2"
      :total="total"
      :data-list="dataList"
      row-key="upc"
      @search="search"
      @handleCurrentChange="handleCurrentChange"
      @handleSizeChange="handleSizeChange"
      @selectionChange="selectionChange"
      @edit="edit"
    >
      <template v-slot:imageUrl="{ scope }">
        <el-image class="mainImg" :src="scope.row.imageUrl || '' | transImgUrl" :preview-src-list="[scope.row.imageUrl || ''] | transImgUrl" />
      </template>
      <template v-slot:sku="{ scope }">
        <span class="el-button--text el-button--mini" @click="viewDetail(scope.row)">{{ scope.row.sku }}</span>
      </template>
      <div slot="right" name="right">
        <el-button :disabled="!multipleSelection.length" size="mini" type="primary" round @click="batchEdit">批量编辑</el-button>
      </div>
    </essTable>
    <batch-edit ref="batchEdit" :dialog-loading="dialogLoading" @batchEditSubmit="batchEditSubmit" />
  </div>
</template>

<script>
import searchHead from '@/views/coi/commodityM/components/searchHead.vue'
import essTable from '@/components/eTable/eTable.vue'
import batchEdit from '@/views/coi/commodityM/components/batchEdit.vue'
import { commodityTableList } from '@/views/coi/commonJs/tableHeadList'
import { commoditylibraryList, commoditylibraryExport, batchUpdateSkuAllChannel, commoditylibraryExports } from '@/api/coi/onlineTaskAPI/sku'
import moment from 'moment'
import eventBus from '@/utils/eventBus'
import { authentication, stringToArray } from '@/utils/processingData.js'
import { goodsType_CBEC, goodsType_NO_CBEC } from '@/views/coi/commonJs/dictionary.js'
import { hasPower } from '@/views/coi/channelInventory/js/role'

export default {
  name: 'CommodityLibrary',
  components: {
    searchHead,
    essTable,
    batchEdit
  },
  filters: {
    transImgUrl(url) {
      return authentication(url)
    }
  },
  mixins: [hasPower],
  props: {
    menuName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      resizeObserverEle: ['.app-main', '.app-container'],
      otherContainerBox: ['.app-container', '.checkComponent'],
      searchData: {
        pageNum: 0,
        pageSize: 10
      },
      theadList: commodityTableList,
      total: 0,
      dataList: [],
      loading: false,
      routerName: this.$route.name,
      processDataList: [], // 操作日志
      dialogLoading: false,
      multipleSelection: [],
      windowValue: window.appConfig.hiddenNewProducts
    }
  },
  activated() {
    this.handleCurrentChange(1)
  },
  mounted() {
    this.search()
  },
  methods: {
    // 点击检索按钮执行
    async search() {
      this.$refs.table.clearSelection()
      try {
        this.loading = true
        const obj = this.handleData()
        if (obj.finelineNbrList && obj.finelineNbrList.length > 0) {
          if (!obj.deptNbr) return this.$message.error('部门不能为空')
        }
        if (obj.deptNbr) {
          if (!obj.finelineNbrList) return this.$message.error('Fineline不能为空')
          if (obj.finelineNbrList && obj.finelineNbrList.length <= 0) {
            this.$message.error('Fineline不能为空')
            delete obj.finelineNbrList
            return
          }
        }
        const { result } = await this.query(obj)
        this.dataList = []
        if (result) {
          this.total = result.total
          this.dataList = result.data
          this.dataList.forEach((item) => {
            item.createdTime = this.transDate(item.createdTime)
            item.updatedTime = this.transDate(item.updatedTime)
          })
        }
      } finally {
        this.loading = false
      }
    },
    transDate(v) {
      if (v === null) {
        return ''
      }
      return moment(v).format('YYYY-MM-DD HH:mm:ss')
    },
    async query(searchData) {
      return await commoditylibraryList(searchData)
    },
    handleData(flag = false) {
      const searchData = JSON.parse(JSON.stringify(this.searchData))
      if ('skuList' in searchData) searchData.skuList = stringToArray(searchData.skuList, /[\n\r]/) // upc(不含检验码)
      if ('finelineNbrList' in searchData) searchData.finelineNbrList = stringToArray(searchData.finelineNbrList, /[\n\r]/) // 细分类
      if (!window.hidden_CBEC_iteration && !this.isAdministration) {
        searchData.notInGoodsType = []
        console.log(this.isECOperate, this.hasAuthority)
        if (!this.isECOperate) searchData.notInGoodsType.push(...goodsType_CBEC.map((_) => _.value))
        if (!this.hasAuthority) searchData.notInGoodsType.push(...goodsType_NO_CBEC.map((_) => _.value))
      }
      // if (flag && Array.isArray(this.multipleSelection) && this.multipleSelection.length) searchData.skuList = this.multipleSelection.map((_) => _.skuCode)
      return searchData
    },
    // 重置检索条件
    reset() {
      this.searchData = {
        pageSize: 10,
        pageNum: 0
      }
      this.search()
    },
    // 导出
    async download() {
      const date = moment(new Date()).format('YYYY-MM-DD')
      commoditylibraryExport(this.searchData, `线上商品库 ${date}`)
    },
    // 下载
    downloadExc() {
      const date = moment(new Date()).format('YYYY-MM-DD')
      commoditylibraryExports(this.handleData(true), `线上SKU商品库 ${date}`)
    },
    // 分页器
    handleCurrentChange(val) {
      this.searchData.pageNum = val - 1
      this.search()
    },
    handleSizeChange(val) {
      this.searchData.pageSize = val
      this.handleCurrentChange(1)
    },
    selectionChange(val) {
      this.multipleSelection = val
    },
    batchEdit() {
      this.$refs.batchEdit.form = {}
      this.$refs.batchEdit.dialogVisible = true
    },
    batchEditSubmit(form) {
      const upcList = []
      this.multipleSelection.forEach((item) => {
        upcList.push(item.upc)
      })
      const param = {
        upcNbrList: upcList,
        area: form.area,
        premiumPrice: form.premiumPrice
      }
      batchUpdateSkuAllChannel(param).then((res) => {
        if (res) {
          this.$message({
            type: 'sucess',
            message: '编辑成功！'
          })
        }
        this.handleCurrentChange(1)
      })
      this.$refs.batchEdit.loading = false
      this.$refs.batchEdit.dialogVisible = false
    },
    edit(scope) {
      eventBus.$emit('setTagName', scope.row.skuName)
      this.$router.push({
        path: `/commodityM/commodityEdit/${scope.row.upc}/edit/${this.$route.name}/0`,
        query: { tab: this.menuName }
      })
    },
    viewDetail(row) {
      eventBus.$emit('setTagName', row.skuName)
      this.$router.push({
        path: `/commodityM/commodityEdit/${row.upc}/detail/${this.$route.name}/0`,
        query: { tab: '' }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.purchase {
  height: calc(100%);
}
/deep/ .el-dialog__body {
  padding: 10px 20px;
  overflow-y: auto;
  max-height: 75vh;
}
/deep/ .el-dialog__footer {
  padding: 10px 20px;
}
.details {
  /deep/ .el-dialog__body {
    padding: 0;
    padding-bottom: 20px;
  }
}
.remark {
  margin: 8px 0;
  display: flex;
  justify-content: flex-start;
  .remarkTitle {
    width: 70px;
    line-height: 20px;
  }
  .remarkList {
    flex: 1;
    line-height: 20px;
  }
}
.mainImg {
  max-width: 50px;
  max-height: 50px;
}
</style>
